﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net;

/// <summary>
/// Summary description for Common
/// </summary>
public class Common
{
    public Common()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public const int HOURTIMEOUT = 30;

  
    public const string ASCENDING = " ASC";
    public const string DESCENDING = " DESC";
    public static System.DateTime DateMin = Convert.ToDateTime("01/01/1900");
    public static System.DateTime DateMax = Convert.ToDateTime("01/01/2050");
    public static System.DateTime CacheExpiration = DateTime.Now.AddDays(1);
    public const string UPLOAD_DOCUMENT_PATH = "/Document";
    public const string UPLOAD_AVARTAR_PATH = "Admin/Resource/Avartar";
    public const string UPLOAD_BANER_PATH = "UpLoad/baner";
    public const string UPLOAD_ADS_PATH = "UpLoad/ads";
    public const string UPLOAD_AVATAR_PATH = "UpLoad/avartar";
      public const string MSG_ERROR = "box-error";
    public const string MSG_WARNING = "box-warning";
    public const string MSG_INFO = "box-info";
    public const string MSG_SUCCESS = "box-success";
    public const long UPLOAD_IMAGE_MAXSIZE = 512000;
    public const string ERROR_TEMPLATE = "<li>{0}</li>";
    
    public enum HashMethod
    {
        MD5,
        SHA1,
        SHA384
    }
    public enum eStatus
    {
        Active = 1, //public
        Deactive = 0, //drop
        Delete=2 //Delete
    }

   public static string GenerateHashDigest(string source, HashMethod algorithm)
    {
        HashAlgorithm hashAlgorithm = null;

        //' Create crypto service provider
        switch (algorithm)
        {
            case HashMethod.MD5:
                hashAlgorithm = new MD5CryptoServiceProvider();
                break;
            case HashMethod.SHA1:
                hashAlgorithm = new SHA1CryptoServiceProvider();
                break;
            case HashMethod.SHA384:
                hashAlgorithm = new SHA384Managed();
                break;
            default:
                break;
            // Error case.
        }

        //' Generate hash
        byte[] byteValue = Encoding.UTF8.GetBytes(source);
        byte[] hashValue = hashAlgorithm.ComputeHash(byteValue);

        //' Return hash string
        return Convert.ToBase64String(hashValue);

    }

    public static string GenerateHashDigestMD5(string source, HashMethod algorithm)
    {
        HashAlgorithm hashAlgorithm = null;

        //' Create crypto service provider
        switch (algorithm)
        {
            case HashMethod.MD5:
                hashAlgorithm = new MD5CryptoServiceProvider();
                break;
            case HashMethod.SHA1:
                hashAlgorithm = new SHA1CryptoServiceProvider();
                break;
            case HashMethod.SHA384:
                hashAlgorithm = new SHA384Managed();
                break;
            default:
                break;
            // Error case.
        }

        //' Generate hash
        byte[] byteValue = Encoding.UTF8.GetBytes(source);
        byte[] hashValue = hashAlgorithm.ComputeHash(byteValue);

        //' Return hash string
        return BitConverter.ToString(hashValue).Replace("-", "").ToLowerInvariant();
    }

    public static void WriteLog(string errormess, string errorsource)
    {
        TextWriter tW = default(TextWriter);
        string Table = "";
        if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\\\Errorlog"))
        {
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\\\Errorlog");
        }

        tW = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\\\Errorlog\\\\log.log", true);
        tW.WriteLine(DateTime.Now.ToString() + "----Object : " + Table + "-----Message : " + errormess + "-----Source : " + errorsource);
        tW.WriteLine("------------------------------------END---------------------------------------------------------");
        tW.Close();
    }

    public static void WriteLogSecurity(string logmessage)
    {
        TextWriter tW = default(TextWriter);

        if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\\\Error"))
        {
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\\\Error");
        }

        tW = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\\\Error\\\\Securitylog.log", true);
        tW.WriteLine(DateTime.Now.ToString() + ":  " + HttpContext.Current.User.Identity.Name + "----- Thao tac : " + logmessage);
        //tW.WriteLine("------------------------------------END---------------------------------------------------------")
        tW.Close();
    }

   
    public static string FormatDate(string strDate, char token)
    {
        string[] arrToken = strDate.Split(token);
        return arrToken[1] + token + arrToken[0] + token + arrToken[2];
    }
  

    #region "Kill Char"
    public static string KillChar(string input)
    {
        string[] badChars = {
		"select",
		"update",
		"drop",
		";",
		"--",
		"insert",
		"delete",
		"xp_",
		"sysobjects",
		"syscolumns",
		"'"
	};
        foreach (string badChar in badChars)
        {
            input = input.Replace(badChar, "");
        }
        return input.Trim();
    }
    #endregion

    //This function is used to encode an string to MD5 format
    public static string GenerateHash(string SourceText)
    {
        //Create an encoding object to ensure the encoding standard for the source text
        UnicodeEncoding Ue = new UnicodeEncoding();
        //Retrieve a byte array based on the source text
        byte[] ByteSourceText = Ue.GetBytes(SourceText);
        //Instantiate an MD5 Provider object
        MD5CryptoServiceProvider Md5 = new MD5CryptoServiceProvider();
        //Compute the hash value from the source
        byte[] ByteHash = Md5.ComputeHash(ByteSourceText);
        //And convert it to String format for return
        return Convert.ToBase64String(ByteHash);
    }

    //Check valid date
    public static bool checkDate(string year1, string month1, string day1)
    {
        bool f = true;
        try
        {
            Int32 year = Convert.ToInt32(year1);
            Int32 month = Convert.ToInt32(month1);
            Int32 day = Convert.ToInt32(day1);

            if (year < 1900 | year > 9999 | month < 1 | month > 12 | day < 1 | day > 31)
            {
                return false;
            }
            else
            {
                if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10 | month == 12)
                {
                    if (day < 0 | day > 31)
                    {
                        return false;
                    }
                }
                else if (month == 4 | month == 6 | month == 9 | month == 11)
                {
                    if (day < 0 | day > 30)
                    {
                        return false;
                    }
                }
                else
                {
                    if (year % 4 == 0 & (year % 100 != 0 | year % 400 == 0))
                    {
                        if (day < 0 | day >= 30)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (day < 0 | day >= 29)
                        {
                            return false;
                        }
                    }
                }
            }

        }
        catch (Exception ex)
        {
            return false;
        }

        return true;

    }

    public static string ReadFile(string filename)
    {
        string sContent = "";
        try
        {
            string filepath = HttpContext.Current.Server.MapPath(filename);
            StreamReader objStreamReader = File.OpenText(filepath);
            sContent = objStreamReader.ReadToEnd();
            objStreamReader.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return sContent;
    }
    public static string GetKeyWord(string sContent)
    {
        try
        {
            string[] sArrayTemplateA = {
			"á",
			"à",
			"ạ",
			"ả",
			"ã",
			"â",
			"ấ",
			"ầ",
			"ẩ",
			"ẫ",
			"ậ",
			"ă",
			"ắ",
			"ằ",
			"ẳ",
			"ẵ",
			"ặ"
		};
            foreach (String i in sArrayTemplateA)
            {
                sContent = sContent.Replace(i,"a");
                sContent = sContent.Replace(i.ToUpper(), "A");
            }

            string[] sArrayTemplateE = {
			"é",
			"è",
			"ẻ",
			"ẽ",
			"ẹ",
			"ê",
			"ế",
			"ề",
			"ể",
			"ễ",
			"ệ"
		};
            foreach (String i in sArrayTemplateE)
            {
                sContent = sContent.Replace(i, "e");
                sContent = sContent.Replace(i.ToUpper(),"E");
            }

            string[] sArrayTemplateU = {
			"ú",
			"ù",
			"ủ",
			"ũ",
			"ụ",
			"ư",
			"ứ",
			"ừ",
			"ử",
			"ữ",
			"ự"
		};
            foreach (String i in sArrayTemplateU)
            {
              
                sContent = sContent.Replace(i, "u");
                sContent = sContent.Replace(i.ToUpper(),"U");
            }

            string[] sArrayTemplateI = {
			"í",
			"ì",
			"ỉ",
			"ĩ",
			"ị"
		};
            foreach (String i in sArrayTemplateI)
            {
                sContent = sContent.Replace(i, "i");
                sContent = sContent.Replace(i.ToUpper(),"I");
            }

            string[] sArrayTemplateO = {
			"ó",
			"ò",
			"ỏ",
			"õ",
			"ọ",
			"ô",
			"ố",
			"ồ",
			"ổ",
			"ỗ",
			"ộ",
			"ơ",
			"ớ",
			"ờ",
			"ở",
			"ỡ",
			"ợ"
		};
            foreach (String i in sArrayTemplateO)
            {
                sContent = sContent.Replace(i, "o");
                sContent = sContent.Replace(i.ToUpper(), "O");
            }

            string[] sArrayTemplateD = { "đ" };
            foreach( String i in sArrayTemplateD)
            {
                sContent = sContent.Replace(i, "d");
                sContent = sContent.Replace(i.ToUpper(), "D");
            }

        }
        catch (Exception ex)
        {
            Common.WriteLog(ex.Message, ex.StackTrace);
        }
        return sContent;
    }

    public static bool IsNumber(string sInput)
    {
       
        
            return Regex.IsMatch(sInput, @"[^0-9]");
      
    }

    //This function is used to check input string is a valid email or not
    public static bool isValidEmail(string emailAddress)
    {
        return Regex.IsMatch(emailAddress, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }

    public static bool isLettersAndNumberOnly(string str)
    {
        return Regex.IsMatch(str, @"^[a-zA-Z0-9]+$");
    }
    public static string dFormatShort(DateTime pDate)
    {
        string rStr = "";
        string iDate=pDate.DayOfWeek.ToString().ToUpper();
        switch (iDate)
        {
            case "SUNDAY":
                rStr = "Ch&#7911; nh&#7853;t";
                break;
            case "MONDAY":
                rStr = "Th&#7913; hai";
                break;
            case "TUESDAY":
                rStr = "Th&#7913; ba";
                break;
            case "WEDNESDAY":
                rStr = "Th&#7913; t&#432;";
                break;
            case "THURSDAY":
                rStr = "Th&#7913; n&#259;m";
                break;
            case "FRIDAY":
                rStr = "Th&#7913; s&#225;u";
                break;
            case "SATURDAY":
                rStr = "Th&#7913; b&#7843;y";
                break;
        }

        rStr = rStr + " , " + pDate.Day + "/" + pDate.Month + "/" + pDate.Year + "&nbsp;&nbsp;";

        if (pDate.Hour < 10)
            rStr = rStr + "0" + pDate.Hour + ":";
        else
            rStr = rStr + pDate.Hour + ":";
        if (pDate.Minute < 10)
            rStr = rStr + "0" + pDate.Minute;
        else
            rStr = rStr + pDate.Minute;

        return rStr;
    }
   
    public static string FormatMultiline(string text)
    {
        if (text == null)
        {
            return "";
        }
        string result = text;
        if (result.Length > 0)
        {
            result = result.Replace("\r\n", "<br />");
            return result;
        }
        else
        {
            return text;
        }
    }
   
}